import socket
import struct


def receive_multicast_messages():
    # 创建 UDP 套接字
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    # 绑定到本地地址和端口
    sock.bind(("0.0.0.0", 42102))

    # 加入组播组
    group = socket.inet_aton('224.0.2.2')

    # 要绑定的IP地址
    ip_address = "192.168.147.2"

    # 将IP地址转换为网络字节序
    ip_bytes = socket.inet_aton(ip_address)

    # 创建组播请求结构体
    # mreq = struct.pack('4sL', group, socket.INADDR_ANY)
    mreq = struct.pack('4s4s', group, ip_bytes)

    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

      # 设置转发目标的地址和端口
    forward_ip = "192.168.1.100"
    forward_port = 5000
    # forward_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    try:
        # 接收组播消息
        while True:
            data, address = sock.recvfrom(1024)
            print("Received message:", data.decode(), "from", address)
            # 转发收到的消息到指定的 IP 和端口
       
            # forward_sock.sendto(data, (forward_ip, forward_port))
            
    finally:
        sock.close()
        # forward_sock.close()

if __name__ == "__main__":
    receive_multicast_messages()
  